﻿using Jaina;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace YS.K12.Application.IoT.CommandHandler
{
    /// <summary>
    /// 命令处理程序基类
    /// </summary>
    /// <typeparam name="T">CommandHandler</typeparam>
    public abstract class CommandHandlerBase<T> : IEventSubscriber, IDisposable
    {
        public readonly ILogger _logger;
        protected readonly IServiceScope _serviceScope;
        public CommandHandlerBase(ILogger<T> logger, IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _serviceScope = scopeFactory.CreateScope();
        }
        public virtual Task HandleAsync(EventHandlerExecutingContext context)
        {
            throw new Exception("必须重写该方法");
        }
        public void Dispose()
        {
            _serviceScope.Dispose();
        }
        public string MapString<TU>(TU tU, System.Text.Encodings.Web.JavaScriptEncoder? encoder = null)
        {
            encoder ??= System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

            JsonSerializerOptions serializerOptions = new JsonSerializerOptions() { Encoder = encoder };

            return JsonSerializer.Serialize(tU, serializerOptions);
        }
    }

}
